from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer
from sqlalchemy.orm import Session

from ..database import get_db
from ..models.user import User
from ..auth.auth import authenticate_user, create_access_token, get_current_active_user
from ..auth.schemas import Token, UserLogin, UserResponse
from ..config import settings

router = APIRouter()

@router.post("/login", response_model=Token)
async def login(user_credentials: UserLogin, db: Session = Depends(get_db)):
    """用户登录"""
    user = authenticate_user(db, user_credentials.username, user_credentials.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token = create_access_token(data={"sub": user.username})
    return {"access_token": access_token, "token_type": "bearer"}

@router.get("/me", response_model=UserResponse)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
    """获取当前用户信息"""
    return current_user

@router.get("/config")
async def get_config(current_user: User = Depends(get_current_active_user)):
    """获取前端配置信息"""
    return {
        "dify_iframe_url": settings.DIFY_IFRAME_URL,
        "app_name": settings.APP_NAME,
        "version": settings.VERSION
    }

@router.post("/logout")
async def logout(current_user: User = Depends(get_current_active_user)):
    """用户登出"""
    # 记录退出日志
    print(f"👤 用户 {current_user.username} ({current_user.full_name}) 退出登录")
    
    # 返回成功消息
    return {
        "message": "退出登录成功",
        "user": current_user.username,
        "timestamp": "logout_successful"
    } 